import sqlite3
import copy, os
from SqliteHandler import SqliteHandler
from SqlDict import SqlDict



class Table1rate:

    
    rate_example = {
                    '预备费':0,
                    '建设利息':0,
                    }
    
    def __init__(self, prototype='book1', *args, **kwargs):

        # prototype 参数 book1 电源设备 book2 有线设备 book3 无线设备 book4 线路工程 book5 管道工程

        self.rate = copy.deepcopy(self.rate_example)
        self.path = kwargs.get('path')
        self.conn = SqliteHandler(self.path)
        self.get_rate(prototype)

        self.conn.close()

    def getrate(self):
        return self.rate

    def customrate(self, *args, **kwargs):
        
        rate = self.getrate()
        for i in kwargs:
            self.filldictitem(rate, i, kwargs[i])
        
        return rate



    def get_rate(self, prototype):
        # 'Reserve'为预备费, 'interest'为建设利息
        names = ['预备费', '建设利息']
        dicttool = SqlDict()
        names_db = [dicttool.geth2edict()[i] for i in names]
        for index, i in enumerate(names_db):
            data = self.conn.select(i)
            data = self.cursor2list(data)
            for j in data:
                if j [1] == prototype:
                    self.rate[names[index]] = j[2]
                    break
        


    def cursor2list(self, cursor):
        # 将cursor可迭代对象转换为list
        mylist = []
        for i in cursor:
            temp = []
            for j in i:
                temp.append(j)
            mylist.append(temp)

        return mylist

    def filldictitem(self, d, key, item):
        # 将item写入复杂字典对应的key,key不能有重复
        for i in d:
            if not isinstance(d[i], dict):
                if i == key:
                    d[i] = item
                    return
            else:
                self.filldictitem(d[i], key, item)

if __name__ == "__main__":
    BASE_DIR = os.path.dirname(os.path.abspath(__file__))
    path = os.path.join(BASE_DIR, 'db/rate.db')
    print(path)
    test = Table1rate('book5', path=path)
    data = test.getrate()
    print(data)